class AIAssistant:
    """AI助手父类，包含所有助手的基本属性和方法"""

    def __init__(self, aid, name, assistant_type, version, is_online, score):
        self.aid = aid  # 编号
        self.name = name  # 名称
        self.type = assistant_type  # 类型
        self.version = version  # 版本号
        self.is_online = is_online  # 是否在线
        self.score = score  # 能力评分

    def __str__(self):
        status = "🟢在线" if self.is_online else "🔴离线"
        return f"ID: {self.aid}, 名称: {self.name}, 类型: {self.type}, 版本: {self.version}, 状态: {status}, 能力评分: {self.score} [{self.type}]"

    def get_basic_info(self):
        """返回基本信息，用于列表展示"""
        status = "在线" if self.is_online else "离线"
        return f"ID: {self.aid}, 名称: {self.name}, 类型: {self.type}, 版本: {self.version}, 状态: {status}, 能力评分: {self.score} [{self.type}]"

    def start_service(self):
        """启动服务"""
        if self.is_online:
            return False, f"助手【{self.name}】已在运行。"
        self.is_online = True
        return True, f"✅ 助手【{self.name}】已启动。"

    def stop_service(self):
        """停止服务"""
        if not self.is_online:
            return False, f"助手【{self.name}】已停止。"
        self.is_online = False
        return True, f"✅ 助手【{self.name}】已停止。"

    def assign_task(self, task):
        """分配任务"""
        if not self.is_online:
            return False, f"❌ {self.name} 当前离线，无法执行任务。"
        return True, f"✅ 已为【{self.name}】分配任务: {task}\n{self.process_task(task)}"

    def process_task(self, task):
        """处理任务，子类可重写"""
        return f"【{self.type}】正在处理任务: {task}"


class DataAnalysisAssistant(AIAssistant):
    """数据分析助手子类"""

    def __init__(self, aid, name, version, is_online, score, supported_formats):
        super().__init__(aid, name, "数据分析助手", version, is_online, score)
        self.supported_formats = supported_formats  # 支持的数据格式

    def __str__(self):
        base_info = super().__str__()
        return f"{base_info}\n支持的数据格式: {', '.join(self.supported_formats)}"

    def process_task(self, task):
        return f"【数据分析助手】正在分析任务: {task}\n将使用支持的格式进行处理: {', '.join(self.supported_formats)}"


class ImageGenerationAssistant(AIAssistant):
    """图片生成助手子类"""

    def __init__(self, aid, name, version, is_online, score, max_resolution):
        super().__init__(aid, name, "图片生成助手", version, is_online, score)
        self.max_resolution = max_resolution  # 最大分辨率

    def __str__(self):
        base_info = super().__str__()
        return f"{base_info}\n最大分辨率: {self.max_resolution}"

    def process_task(self, task):
        return f"【图片生成助手】正在生成图片: {task}\n将以最大分辨率 {self.max_resolution} 生成"


class TextGenerationAssistant(AIAssistant):
    """文本生成助手子类"""

    def __init__(self, aid, name, version, is_online, score, supported_languages):
        super().__init__(aid, name, "文本生成助手", version, is_online, score)
        self.supported_languages = supported_languages  # 支持的语言

    def __str__(self):
        base_info = super().__str__()
        return f"{base_info}\n支持的语言: {', '.join(self.supported_languages)}"

    def process_task(self, task):
        return f"【文本生成助手】正在生成文本: {task}\n支持的语言: {', '.join(self.supported_languages)}"


class TranslationAssistant(AIAssistant):
    """翻译助手子类"""

    def __init__(self, aid, name, version, is_online, score, language_pairs):
        super().__init__(aid, name, "翻译助手", version, is_online, score)
        self.language_pairs = language_pairs  # 支持的语言对

    def __str__(self):
        base_info = super().__str__()
        return f"{base_info}\n支持的语言对: {', '.join(self.language_pairs)}"

    def process_task(self, task):
        return f"【翻译助手】正在翻译: {task}\n支持的语言对: {', '.join(self.language_pairs)}"


class VoiceAssistant(AIAssistant):
    """语音助手子类"""

    def __init__(self, aid, name, version, is_online, score, noise_cancellation):
        super().__init__(aid, name, "语音助手", version, is_online, score)
        self.noise_cancellation = noise_cancellation  # 是否支持降噪

    def __str__(self):
        base_info = super().__str__()
        noise_support = "支持" if self.noise_cancellation else "不支持"
        return f"{base_info}\n降噪功能: {noise_support}"

    def process_task(self, task):
        noise_support = "支持" if self.noise_cancellation else "不支持"
        return f"【语音助手】正在处理语音任务: {task}\n降噪功能: {noise_support}"


class AIManager:
    """AI助手管理器类，用于管理所有AI助手"""

    def __init__(self, capacity=10):
        self.capacity = capacity  # 最大容量
        self.assistants = []  # 存储AI助手的数组
        self._initialize_default_assistants()

    def _initialize_default_assistants(self):
        """初始化一些默认的AI助手"""
        self.assistants.append(VoiceAssistant(101, "小智", "v1.2", True, 85, True))
        self.assistants.append(TextGenerationAssistant(102, "文小助", "v2.0", True, 92, ["中文", "英文", "日文"]))
        self.assistants.append(ImageGenerationAssistant(103, "图灵", "v1.5", False, 88, "4K"))
        self.assistants.append(DataAnalysisAssistant(104, "数小析", "v1.0", True, 79, ["CSV", "Excel", "JSON"]))
        self.assistants.append(TranslationAssistant(105, "翻译精灵", "v2.1", False, 95, ["中->英", "英->中", "中->日"]))

    def find_assistant_by_id(self, aid):
        """根据ID查找助手"""
        for assistant in self.assistants:
            if assistant.aid == aid:
                return assistant
        return None

    def list_all_assistants(self):
        """列出所有助手"""
        if not self.assistants:
            print("暂无AI助手信息")
            return

        print("所有AI助手列表：")
        for i, assistant in enumerate(self.assistants, 1):
            print(f"{i}. {assistant.get_basic_info()}")

    def query_assistant_detail(self, aid):
        """查询助手详情"""
        assistant = self.find_assistant_by_id(aid)
        if assistant:
            print(f"✅ 查询结果: {assistant}")
        else:
            print(f"❌ 未找到ID为{aid}的AI助手")

    def add_assistant(self):
        """添加新的AI助手"""
        if len(self.assistants) >= self.capacity:
            print(f"❌ 无法添加新助手，已达到最大容量({self.capacity})")
            return

        try:
            aid = int(input("请输入ID: "))

            # 检查ID是否已存在
            if self.find_assistant_by_id(aid):
                print(f"❌ ID为{aid}的助手已存在")
                return

            name = input("请输入名称: ")

            # 选择助手类型
            print("请选择助手类型:")
            print("1. 数据分析助手")
            print("2. 图片生成助手")
            print("3. 文本生成助手")
            print("4. 翻译助手")
            print("5. 语音助手")

            type_choice = int(input("请选择(1-5): "))

            version = input("请输入版本号: ")
            is_online = input("是否在线？(1-是, 0-否): ") == "1"
            score = int(input("请输入能力评分(0-100): "))

            # 根据类型创建不同的子类实例
            if type_choice == 1:
                formats = input("请输入支持的数据格式(用逗号分隔): ").split(',')
                formats = [f.strip() for f in formats]
                assistant = DataAnalysisAssistant(aid, name, version, is_online, score, formats)
            elif type_choice == 2:
                resolution = input("请输入最大分辨率: ")
                assistant = ImageGenerationAssistant(aid, name, version, is_online, score, resolution)
            elif type_choice == 3:
                languages = input("请输入支持的语言(用逗号分隔): ").split(',')
                languages = [l.strip() for l in languages]
                assistant = TextGenerationAssistant(aid, name, version, is_online, score, languages)
            elif type_choice == 4:
                pairs = input("请输入支持的语言对(用逗号分隔): ").split(',')
                pairs = [p.strip() for p in pairs]
                assistant = TranslationAssistant(aid, name, version, is_online, score, pairs)
            elif type_choice == 5:
                noise_cancel = input("是否支持降噪功能？(1-是, 0-否): ") == "1"
                assistant = VoiceAssistant(aid, name, version, is_online, score, noise_cancel)
            else:
                print("❌ 无效的类型选择")
                return

            self.assistants.append(assistant)
            print(f"✅ 助手【{name}】添加成功！")

        except ValueError:
            print("❌ 输入格式错误，请检查您的输入")

    def modify_assistant(self):
        """修改助手信息"""
        try:
            aid = int(input("请输入ID: "))
            assistant = self.find_assistant_by_id(aid)

            if not assistant:
                print(f"❌ 未找到ID为{aid}的AI助手")
                return

            print("可修改属性列表为：name, type, version, online, score")
            attr_value = input("请输入要修改的属性和值，用空格分割: ").strip().split()

            if len(attr_value) != 2:
                print("❌ 输入格式错误，请使用'属性 值'的格式")
                return

            attr, value = attr_value

            # 根据属性进行修改
            if attr == "name":
                assistant.name = value
            elif attr == "type":
                # 类型修改需要创建新实例，比较复杂，这里简化处理
                print("❌ 类型修改暂不支持")
                return
            elif attr == "version":
                assistant.version = value
            elif attr == "online":
                assistant.is_online = (value == "1" or value.lower() == "yes" or value.lower() == "true")
            elif attr == "score":
                assistant.score = int(value)
            else:
                print(f"❌ 未知属性: {attr}")
                return

            print(f"✅ 助手【{aid}】修改成功！")

        except ValueError:
            print("❌ 输入格式错误，请检查您的输入")

    def delete_assistant(self):
        """删除助手"""
        try:
            aid = int(input("请输入要删除的AI助手ID: "))
            assistant = self.find_assistant_by_id(aid)

            if not assistant:
                print(f"❌ 未找到ID为{aid}的AI助手")
                return

            self.assistants.remove(assistant)
            print(f"✅ 助手【{assistant.name}】已删除。")

        except ValueError:
            print("❌ 输入格式错误，请检查您的输入")

    def start_assistant_service(self):
        """启动助手服务"""
        try:
            aid = int(input("请输入要启动的AI助手ID: "))
            assistant = self.find_assistant_by_id(aid)

            if not assistant:
                print(f"❌ 未找到ID为{aid}的AI助手")
                return

            success, message = assistant.start_service()
            print(message)

        except ValueError:
            print("❌ 输入格式错误，请检查您的输入")

    def stop_assistant_service(self):
        """停止助手服务"""
        try:
            aid = int(input("请输入要停止的AI助手ID: "))
            assistant = self.find_assistant_by_id(aid)

            if not assistant:
                print(f"❌ 未找到ID为{aid}的AI助手")
                return

            success, message = assistant.stop_service()
            print(message)

        except ValueError:
            print("❌ 输入格式错误，请检查您的输入")

    def assign_task_to_assistant(self):
        """为助手分配任务"""
        try:
            aid = int(input("请输入目标AI助手ID: "))
            assistant = self.find_assistant_by_id(aid)

            if not assistant:
                print(f"❌ 未找到ID为{aid}的AI助手")
                return

            task = input("请输入任务内容: ")
            success, message = assistant.assign_task(task)
            print(message)

        except ValueError:
            print("❌ 输入格式错误，请检查您的输入")

    def show_statistics(self):
        """显示系统统计信息"""
        total = len(self.assistants)
        online = sum(1 for a in self.assistants if a.is_online)
        offline = total - online

        if total == 0:
            avg_score = 0
        else:
            avg_score = sum(a.score for a in self.assistants) / total

        print("\n系统统计信息：")
        print(f"总助手数: {total}")
        print(f"在线助手数: {online}")
        print(f"离线助手数: {offline}")
        print(f"平均能力评分: {avg_score:.2f}")


def main():
    """主函数，程序入口"""
    print("欢迎使用 AI助手管理器 v1.0")
    manager = AIManager()

    while True:
        print("\n========== AI助手管理器 ==========")
        print("1. 查看所有AI助手列表")
        print("2. 根据ID查询助手详情")
        print("3. 添加新的AI助手")
        print("4. 根据ID修改助手信息")
        print("5. 删除AI助手（按ID）")
        print("6. 启动AI助手服务")
        print("7. 停止AI助手服务")
        print("8. 为AI助手分配任务")
        print("9. 显示系统统计信息")
        print("0. 退出系统")
        print("===================================")

        try:
            choice = int(input("请选择操作: "))

            if choice == 0:
                print("感谢使用，再见！")
                break
            elif choice == 1:
                manager.list_all_assistants()
            elif choice == 2:
                aid = int(input("请输入要查询的AI助手ID: "))
                manager.query_assistant_detail(aid)
            elif choice == 3:
                print("添加新AI助手")
                manager.add_assistant()
            elif choice == 4:
                print("修改AI助手数据")
                manager.modify_assistant()
            elif choice == 5:
                manager.delete_assistant()
            elif choice == 6:
                manager.start_assistant_service()
            elif choice == 7:
                manager.stop_assistant_service()
            elif choice == 8:
                manager.assign_task_to_assistant()
            elif choice == 9:
                manager.show_statistics()
            else:
                print("❌ 无效的选择，请输入0-9之间的数字")

        except ValueError:
            print("❌ 输入格式错误，请输入数字")


if __name__ == "__main__":
    main()
